﻿// create a namespace for the application
this.mProton = this.mProton || {};
// this is a function closure
(function () {

    // the application
    function Sound(source, loop, onLoadCompleted) {
        this.src = source;
        this.loop = loop;
        this.onLoadCompleted = onLoadCompleted;
        this.init();
    }

    Sound.prototype = {
        src: null,            // the audio src we are trying to play
        soundInstance: null,  // the soundInstance returned by Sound when we create or play a src
        displayStatus: null,  // the HTML element we use to display messages to the user
        loadProxy: null,
        loop: 1,
        onLoadCompleted: function () { },
        init: function (source) {
            if (!createjs.Sound.initializeDefaultPlugins()) {
                return;
            }
            this.loadProxy = createjs.proxy(this.loadCompleted, this);
            createjs.Sound.addEventListener("fileload", this.loadProxy); // add event listener for when load is completed.
            createjs.Sound.registerSound(this.src); // register sound, which preloads by default
            return this;
        },
        loadCompleted: function () {
            createjs.Sound.removeEventListener("fileload", this.loadProxy); // we only load 1 sound, so remove the listener
            this.onLoadCompleted();
        },
        pause: function () {
            if (this.soundInstance != null)
                this.soundInstance.pause();
        },
        play: function () {
            this.soundInstance = createjs.Sound.play(this.src, "none", 0, 0, this.loop, 1, 0); // start playback and store the soundInstance we are currently play
        },
        resume: function () {
            if (this.soundInstance != null)
                this.soundInstance.resume();
        },
        playOrResume:function() {
            if (this.soundInstance != null)
                this.soundInstance.resume();
            else
                this.soundInstance = createjs.Sound.play(this.src, "none", 0, 0, this.loop, 1, 0); // start playback and store the soundInstance we are currently play
        },
        stop: function () {
            if (this.soundInstance != null)
                this.soundInstance.stop();
        },
        setVolumn: function (volumn) {
            if (this.soundInstance != null)
                this.soundInstance.volume(volumn);
        }
    };
    // add Sound to mProton
    mProton.Sound = Sound;
}());